package me.goldze.mvvmhabit.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import me.goldze.mvvmhabit.R;
import me.goldze.mvvmhabit.utils.StringUtils;

/**
 * @author PACY
 * @date 2021/11/25
 * description: toolbar封装
 */
public class BaseToolbar extends RelativeLayout {
    private String title;
    private boolean showBackIcon;
    private String menu1Text;

    BackClick backClick;

    MenuClick menuClick;

    public TextView titleTv;
    public ImageView leftIcon;
    public TextView menu1_tv;

    public BaseToolbar(Context context) {
        super(context);
    }

    public BaseToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.base_toolbar_view, this, true);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BaseToolbar);
        title = a.getString(R.styleable.BaseToolbar_title);
        showBackIcon = a.getBoolean(R.styleable.BaseToolbar_showBackIcon, true);
        menu1Text = a.getString(R.styleable.BaseToolbar_menu1);
        a.recycle();
    }

    public void setBackClick(BackClick backClick) {
        this.backClick = backClick;
    }

    public void setMenuClick(MenuClick menuClick) {
        this.menuClick = menuClick;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        titleTv = findViewById(R.id.base_title);
        leftIcon = findViewById(R.id.base_left_icon);
        menu1_tv = findViewById(R.id.menu1_tv);
        if (showBackIcon) {
            leftIcon.setVisibility(VISIBLE);
        } else {
            leftIcon.setVisibility(GONE);
        }

        if (StringUtils.isEmpty(menu1Text)) {
            setTitle(title);
        } else {
            setTitleAndMenu1(title, menu1Text);
        }
    }


    public void setTitleAndMenu1(String title, String menu1) {
        menu1_tv.setVisibility(VISIBLE);
        menu1_tv.setText(menu1);
        setTitle(title);

        menu1_tv.setOnClickListener(v -> {
            if (menuClick != null) {
                menuClick.menu1Click();
            }

        });
    }

    /**
     * 设置图标
     *
     * @param iconResource
     */
    public void setLeftIcon(int iconResource) {
        leftIcon.setBackgroundResource(iconResource);
        leftIcon.setVisibility(VISIBLE);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        titleTv.setText(title);
        leftIcon.setOnClickListener((v) -> {
            if (backClick != null) {
                backClick.onBack();
            }

        });
    }

}
